<template>
  <div class="home">
    <div class="title-container" v-if="permersion.search">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入用户姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchModel.status" placeholder="请选择状态">
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >
            搜索</el-button
          >
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="medium"
          @click="handlerAccount"
          v-if="permersion.add"
        >
          新建账户</el-button
        >
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
          >刷新</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        class="elTable"
        ref="tableRef"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="userName" label="用户姓名" align="center" />
        <el-table-column prop="roleName" label="角色名称" align="center" />
        <el-table-column prop="accountPhone" label="登陆账号" align="center" />
        <el-table-column prop="isFirst" label="是否为初始密码" align="center">
          <template slot-scope="{ row }">
            <span v-if="row.isFirst == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="accountType"
          label="正常/停用状态"
          align="center"
          width="100"
        >
          <template #default="{ row }">
            <span v-if="row.status == 1" style="color: #07c160">正常</span>
            <span v-else>停用</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{ row }">
            <!-- <el-button type="primary" size="mini" @click="handlerDetails(row)"
              >详情</el-button
            > -->
            <el-button type="warning" size="mini" @click="handlerEdit(row)"
              >编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handlerReset(row)">
              重置密码
            </el-button>
            <div class="status">
              <el-button
                type="success"
                size="mini"
                @click="handlerStatus(row)"
                v-if="row.status == '0'"
                >启用</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handlerStatus(row)"
                v-else
                >禁用</el-button
              >
            </div>
            <el-button type="danger" size="mini" @click="handlerDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="pagination"
      />
    </el-card>
    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="loginFormRef"
            :rules="rules"
            :model="newAccountModel"
            label-width="90px"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="newAccountModel.userName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="角色名称" prop="roleCode">
              <el-select
                v-model="newAccountModel.roleCode"
                :disabled="detailsDisabled"
              >
                <el-option
                  v-for="item in userData"
                  :key="item.roleCode"
                  :label="item.roleName"
                  :value="item.roleCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="accountPhone">
              <el-input
                type="number"
                v-model="newAccountModel.accountPhone"
                :disabled="detailsDisabled"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false"
          >取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
import { accountConfig } from "@/config/account"
import {
  queryAccountPage,
  updateLAccount,
  ResetPassword,
  deleteAccount,
  deactivate,
  insertUser,
  queryRole
} from "@/api/userControl/account"
import ycDialog from "@/components/pageDialog"
export default {
  data() {
    return {
      userData: [],
      isGlobalMessageShow: false,
      isGlobalMessageBoxShow: false,
      messageTitleDes: "",
      message: "",
      messageBoxSaveShow: false,
      accountConfig,
      tableData: [],
      count: 0,
      pageIndex: 1,
      pageSize: 20,
      drawerTitle: "账户详情",
      detailsDisabled: false, //详情 如果为true代表禁用状态
      selectOptions: [
        {
          label: "正常/停用状态（全部）",
          value: null
        },
        {
          label: "正常",
          value: 1
        },
        {
          label: "禁用",
          value: 0
        }
      ],
      searchModel: {
        userName: "",
        status: "" //正常/停用状态（全部）
      },

      newAccountModel: {
        userName: "",
        roleName: "",
        accountPhone: "",
        id: 0,
        roleCode: ""
      },
      permersion: {
        add: true,
        del: true,
        update: true,
        search: true
      },
      loading: false,
      centerTitle: "",
      rules: {
        userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
        roleCode: [
          { required: true, message: "请选择角色", trigger: "change" }
        ],
        accountPhone: [
          { required: true, trigger: "blur", message: "请输入手机号码" }
        ]
      }
    }
  },
  components: {
    ycDialog
  },
  created() {
    this.getAccountData()
    this.queryRole()
  },
  methods: {
    async queryRole() {
      const data = await queryRole()
      this.userData = data.object
      console.log(data)
    },
    /**
     * 获取表格方法
     */
    async getAccountData(pageIndex = 1, pageSize = 20, tableInfo) {
      this.loading = true
      if (tableInfo) {
        const { userName, status } = tableInfo
        const { object } = await queryAccountPage({
          pageIndex,
          pageSize,
          userName,
          status
        })
        this.tableData = object.data
        this.count = object.count
        this.loading = false
      } else {
        const { object } = await queryAccountPage({
          pageIndex,
          pageSize
        })
        this.tableData = object.data
        this.count = object.count
        this.loading = false
      }
    },
    pagination(pageItem) {
      this.getAccountData(pageItem.page, pageItem.limit)
    },

    /**
     * 修改按钮
     */
    handlerEdit(row) {
      this.centerTitle = "编辑"
      console.log(row, "row")
      this.$refs.ycDialog.dialogVisible = true
      this.$refs.loginFormRef?.clearValidate()
      this.detailsDisabled = false
      this.newAccountModel.userName = row.userName
      this.newAccountModel.roleCode = row.roleCode
      this.newAccountModel.accountPhone = row.accountPhone
      this.newAccountModel.id = row.id
    },
    /**
     * 重置按钮
     */
    async handlerReset({ id }) {
      this.$confirm("确定重置密码吗", "重置操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(async () => {
        const { message } = await ResetPassword({ id })
        if (message == "重置成功") {
          this.getAccountData()
          this.isGlobalMessageShow = true
          this.message = "success"
        } else {
          this.message = "error"
        }
      })
    },
    /**
     * 启用或者禁用按钮
     */
    async handlerStatus({ id, status }) {
      const confirmMessageMap = status == 1 ? "确定禁用吗" : "确定启用吗"
      this.$confirm(confirmMessageMap, "禁用/启用操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(async () => {
        const { message } = await deactivate({ id })
        if (message == "操作成功") {
          this.getAccountData()
          this.isGlobalMessageShow = true
          this.message = "success"
        } else {
          this.message = "error"
        }
      })
    },
    /**
     * 删除按钮
     */
    async handlerDelete({ id }) {
      this.$confirm("确定删除此用户吗", "删除操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        center: true
      }).then(async () => {
        const { message } = await deleteAccount({ id })
        if (message == "删除成功") {
          this.getAccountData()
          this.isGlobalMessageShow = true
          this.message = "success"
        } else {
          this.message = "error"
        }
      })
    },

    // 搜索按钮
    async searchClick() {
      this.getAccountData(1, 20, this.searchModel)
    },
    /**
     * 新建账户
     * */
    async handlerAccount() {
      this.centerTitle = "添加"
      this.detailsDisabled = false
      this.$refs.ycDialog.dialogVisible = true
      Object.keys(this.newAccountModel).forEach((item) => {
        this.newAccountModel[item] = ""
      })
      this.$refs.loginFormRef?.clearValidate()
    },
    dialogSave() {
      this.$refs.loginFormRef.validate(async (v) => {
        if (v) {
          if (this.detailsDisabled) {
            // 详情的确定
            this.$refs.ycDialog.dialogVisible = false
          } else if (this.newAccountModel.id) {
            const { userName, accountPhone, id, roleCode } =
              this.newAccountModel
            const { message, status } = await updateLAccount({
              userName,
              roleCode,
              accountPhone,
              id
            })
            if (status == 200) {
              this.getAccountData()
              this.$refs.ycDialog.dialogVisible = false
              this.$message.success(message)
            } else {
              this.$message.error(message)
            }
          } else {
            const { message, status } = await insertUser(this.newAccountModel)
            if (status == 200) {
              this.getAccountData(1, 20)
              this.$refs.ycDialog.dialogVisible = false
              this.$message.success(message)
            } else {
              this.$message.error(message)
            }
          }
        }
      })
    },
    /**
     * 刷新
     */
    refresh() {
      this.searchModel = {}
      this.getAccountData()
    },
    /**
     * globalMessage的知道按钮的方法
     * */
    receive() {
      this.isGlobalMessageShow = false
    },
    async messageBoxSave(show) {
      this.messageBoxSaveShow = show
    }
  }
}
</script>

<style lang="scss" scoped>
.status {
  display: inline-block;
  padding: 0 10px;
}
.title-container {
  display: flex;
  justify-content: flex-end;
  height: 60px;
  .search-content {
    margin-left: 20px;
    display: flex;
  }
  .addAccount {
    margin: 10px 20px;
  }
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.content {
  height: 600px;

  .drawer-title {
    font-weight: 400;
    font-size: 24px;
    color: #000000;
    text-align: center;
    padding: 36px 0;
  }
  .form {
    padding: 0 10px;
  }
}
.footer {
  height: 360px;
  display: flex;
  align-items: flex-end;
  // justify-content: st-end;
  padding: 5px 20px;
}
</style>
